# coding:utf-8
from pathlib import Path
from typing import Any

from PyQt6.QtCore import QUrl, Qt
from PyQt6.QtWebEngineCore import QWebEnginePage
from PyQt6.QtWidgets import QVBoxLayout, QHBoxLayout, QFileDialog
from bs4 import BeautifulSoup
from loguru import logger
from qfluentwidgets import LineEdit, PrimaryPushButton, FluentIcon, TransparentToolButton, InfoBar, LineEditButton
from qframelesswindow.webengine import FramelessWebEngineView

from common import FileTypeIcon
from components import BaseScrollArea


def download_iconfont(html: str, save_path: str):
    logger.info('开始下载 IconFont 图标库...')
    if isinstance(save_path, str):
        save_path = Path(save_path)
    soup = BeautifulSoup(html, 'lxml')
    li_list = soup.find_all('li')
    for li in li_list:
        svg = li.find('svg')
        if not svg:
            continue
        name = li.find('span', {'class': 'icon-name'}).text.strip()
        svg_path = save_path / f'{name}.svg'
        logger.info(f'正在下载 {name} 图标, 保存路径: {svg_path}')
        svg_path.write_text(str(svg))


class IconFontView(BaseScrollArea):
    title = 'IconFont 图标库下载'
    description = 'IconFont 图标库下载'
    is_shortcut = True
    object_name = 'IconFontView'
    icon = FileTypeIcon.SVG

    def __init__(self, parent=None):
        super().__init__(parent, QVBoxLayout)
        self.horizontalLayout = QHBoxLayout()
        self.lineEdit = LineEdit(self)
        self.savePathLineEdit = LineEdit(self)
        self.folderButton = LineEditButton(FluentIcon.FOLDER, self)
        self.sendButton = TransparentToolButton(FluentIcon.SEND, self)
        self.downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, '下载图标', self)
        self.webView = FramelessWebEngineView(self.scrollAreaWidget)

        self.__initWidgets()

    def __initWidgets(self):
        self.setReturnVisible(True)
        self.lineEdit.setPlaceholderText("请输入 url 地址")
        self.lineEdit.setClearButtonEnabled(True)
        self.savePathLineEdit.setPlaceholderText("请输入保存路径")
        self.savePathLineEdit.setClearButtonEnabled(True)
        self.savePathLineEdit.setReadOnly(True)
        self.sendButton.setToolTip('发送请求')
        self.webView.page().setBackgroundColor(Qt.GlobalColor.transparent)
        self.webView.page().setLifecycleState(QWebEnginePage.LifecycleState.Active)
        self.webView.setStyleSheet('border-radius: 8px;')
        self.savePathLineEdit.hBoxLayout.addWidget(self.folderButton)

        self.lineEdit.setText(
            'https://www.iconfont.cn/collections/detail?spm=a313x.search_index.0.da5a778a4.43523a816mkfWo&cid=20665')

        self.horizontalLayout.addWidget(self.lineEdit)
        self.horizontalLayout.addWidget(self.sendButton)
        self.horizontalLayout.addWidget(self.savePathLineEdit)
        self.horizontalLayout.addWidget(self.downloadButton)

        self.scrollLayout.addLayout(self.horizontalLayout)
        self.scrollLayout.addWidget(self.webView, 1)

        self.sendButton.clicked.connect(self.onSendButtonClicked)
        self.downloadButton.clicked.connect(self.onDownloadButtonClicked)
        self.folderButton.clicked.connect(self.onFolderButtonClicked)

    def onFolderButtonClicked(self):
        path = QFileDialog.getExistingDirectory(self, "选择文件夹", str(Path.home()))
        if path:
            self.savePathLineEdit.setText(path)

    def onSendButtonClicked(self):
        url = self.lineEdit.text()
        logger.info(f'请求 url: {url}')
        self.webView.load(QUrl(url))

    def onDownloadButtonClicked(self):
        self.webView.page().toHtml(self.onHtmlReady)

    def onHtmlReady(self, html):
        save_path = self.savePathLineEdit.text()
        url = self.lineEdit.text()
        if not url:
            InfoBar.error('错误', '请输入 url 地址, 并点击发送请求', duration=3000, parent=self)
            return
        if not save_path:
            InfoBar.error('错误', '请选择保存路径', duration=3000, parent=self)
            return
        self.load(download_iconfont, html, self.savePathLineEdit.text())

    def onFuncSuccess(self, result: Any):
        InfoBar.success('成功', f'图标下载成功, 保存路径: {self.savePathLineEdit.text()}', duration=3000, parent=self)
